package com.example.myapplication3.recyclerView

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication3.Fruit
import com.example.myapplication3.R

class FruitAdapter(val fruitList: List<Fruit>): RecyclerView.Adapter<FruitAdapter.ViewHolder>() {
    inner class ViewHolder(view: View): RecyclerView.ViewHolder(view){
        val fruitImage: ImageView = view.findViewById(R.id.fruitImage)
        val fruitName: TextView = view.findViewById(R.id.fruitName)
    }
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.fruit_item,parent,false)
        val viewHolder = ViewHolder(view)
        viewHolder.itemView.setOnClickListener {
            val position = viewHolder.adapterPosition
            // 关键：判断位置是否有效（避免 index=-1）
            if (position != RecyclerView.NO_POSITION && position < fruitList.size) {
                val fruit = fruitList[position]
                Toast.makeText(parent.context, "clicked: ${fruit.name}", Toast.LENGTH_SHORT).show()
            }  else{
                Toast.makeText(parent.context, "clicked: NULL", Toast.LENGTH_SHORT).show()

            }
        }
        viewHolder.fruitImage.setOnClickListener {
            val position = viewHolder.adapterPosition
            // 关键：判断位置是否有效（避免 index=-1）
            if (position != RecyclerView.NO_POSITION && position < fruitList.size) {
                val fruit = fruitList[position]
                Toast.makeText(parent.context, "clicked: ${fruit.name}", Toast.LENGTH_SHORT).show()
            }  else{
                Toast.makeText(parent.context, "clicked: NULL", Toast.LENGTH_SHORT).show()

            }
        }
        return viewHolder
    }

    override fun onBindViewHolder(
        holder: ViewHolder,
        position: Int
    ) {
        val fruit = fruitList[position]
        holder.fruitImage.setImageResource(fruit.imageId)
        holder.fruitName.text = fruit.name


    }

    override fun getItemCount() = fruitList.size


}